package com.srwl.mytx.activity;

import android.Manifest;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.MenuArrayAdapter;
import com.srwl.mytx.domain.Advertisement;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.domain.LiveRecord;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.Mulct;
import com.srwl.mytx.domain.Reward;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.domain.ViewPosition;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.im.LiveRoomListener;
import com.srwl.mytx.im.listener.ConnectListener;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.LiveService;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.AvatarListView;
import com.srwl.mytx.widget.BottomDialog;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.LiveCountDownView;
import com.srwl.mytx.widget.MulctDialog;
import com.srwl.mytx.widget.MultipleCouponView;
import com.srwl.mytx.widget.OfferDialog;
import com.srwl.mytx.widget.PresentDialog;
import com.srwl.mytx.widget.StopLiveDialog;
import com.starrtc.starrtcsdk.api.XHClient;
import com.starrtc.starrtcsdk.api.XHConstants;
import com.starrtc.starrtcsdk.api.XHCustomConfig;
import com.starrtc.starrtcsdk.api.XHLiveItem;
import com.starrtc.starrtcsdk.api.XHLiveManager;
import com.starrtc.starrtcsdk.apiInterface.IXHLiveManagerListener;
import com.starrtc.starrtcsdk.apiInterface.IXHResultCallback;
import com.starrtc.starrtcsdk.core.audio.StarRTCAudioManager;
import com.starrtc.starrtcsdk.core.im.message.XHIMMessage;
import com.starrtc.starrtcsdk.core.player.StarPlayer;
import com.starrtc.starrtcsdk.core.player.StarPlayerScaleType;
import com.starrtc.starrtcsdk.core.pusher.XHCameraRecorder;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class ChatRoomActivity extends BaseChatRoomActivity implements PresentDialog.InteractionListener, LiveCountDownView.InteractionListener, MultipleCouponView.InteractionListener, PermissionsUtils.IPermissionsResult, MulctDialog.InteractionListener, ConnectListener {

    public static void startActivity(Context context, LiveRoom liveRoom) {
        context.startActivity(new Intent(context, ChatRoomActivity.class).putExtra(Constant.EXTRA_INFO_LIVE_ROOM, liveRoom));
    }

    public static final String CLOSE_CURRENT_LIVE = "关闭当前直播";
    public static final String FORBID_CHAT = "禁言";
    public static final String REMOVE_OUT_LIVE_ROOM = "踢出直播间";
    public static final String OPEN_LIVE = "开放直播";
    public static final String FORBID_LIVE = "禁止直播";
    Context context;
    private final int msgViewHeight = 175;
    private static final int REQUEST_CODE_EDIT_TOPIC = 1;

    @BindView(R.id.live_start_countdown)
    TextView tv_countdownView;
    /* @BindView(R.id.img_icon)
     ImageView iv_anchorIcon;*/
   /* @BindView(R.id.tv_anchor_nick)
    TextView tv_anchorName;*/
    @BindView(R.id.iv_live_room_idle)
    ImageView iv_liveRoomIdle;
    @BindView(R.id.tv_bind_goods_name)
    TextView tv_bindGoodsName;
    @BindView(R.id.present_image)
    ImageView iv_present;
    @BindView(R.id.iv_pass)
    ImageView iv_pass;
    //-------------------------------------
    @BindView(R.id.btn_start)
    Button startBtn;
    @BindView(R.id.iv_switch_light)
    ImageView iv_lightSwitch;
    @BindView(R.id.iv_switch_voice)
    ImageView iv_voiceSwitch;
    @BindView(R.id.iv_switch_camera)
    ImageView iv_cameraSwitch;
    @BindView(R.id.img_bt_close)
    ImageButton closeLive;
    @BindView(R.id.rl_right_menu)
    RelativeLayout rl_rightMenu;
    @BindView(R.id.ll_cover)
    FrameLayout ll_cover;
    @BindView(R.id.avatar_list_view)
    AvatarListView avatarListView;

    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;
    private PresentDialog presentDialog;
    private MulctDialog mulctDialog;
    private long lastClickTime = 0;
    private int countDown;
    //private PresentFragment presentFragment;
    private Handler handler = new Handler();

    private Runnable countDownRunnable = new Runnable() {
        @Override
        public void run() {
            if (countDown > 0) {
                handler.postDelayed(countDownRunnable, 1000);
                handleUpdateCountdown();
                countDown--;
            } else {
                startLive();
            }
        }
    };
    private Runnable watchLiveRunnable = new Runnable() {
        @Override
        public void run() {
            watchLive();
        }
    };
    private Topic fullTopic;
    private Topic advertisementTopic;
    private XHLiveManager liveManager;
    private ArrayList<ViewPosition> mPlayerList = new ArrayList<>();
    private int borderW = 0;
    private int borderH = 0;
    private StarRTCAudioManager starRTCAudioManager;


    @Override
    protected void onActivityCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_chat_room);
        ButterKnife.bind(this);
        final FrameLayout content = findViewById(android.R.id.content);
        if (content != null) {
            rootLayout.setContentView(content.getChildAt(0));
        }
        context = this;
        isAnchor = false;
        couponView.setListener(this);
        initLiveRoom();
        liveRoomService.joinLiveRoom(liveRoom);
        //监听刷新当前页面
        registerBroadcastReceiver();
        initMessageView();
        countDownView.setListener(this);
        //观众端不打开音频
        //mRtcEngine.disableAudio();
        //设置直播间角色 ，true是代表观众，false代表主播
        //setClientRole(Constants.CLIENT_ROLE_AUDIENCE);
        //  joinChannel(liveRoom.getId());

        /***
         *  从服务端加载礼物信息
         *
         *  启动要同时修改  PresentRecyclerViewAdapter 的onBindViewHolder方法
         *                   以及LiveLeftGiftView的setReward方法
         */

        //initData();
        initLocalPrentData();
        initMulctItems();
        showCover();
        initClickListener();
        //对直播间状态进行查询
        loadData();


        rl_rightMenu.setOnClickListener(v -> {
            // mDrawerLayout.openDrawer(ll_topicDetail);
            showPopupWindow(ChatRoomActivity.this, rl_rightMenu);
//            if (TextUtils.equals(myUserInfo.getuId(), liveRoom.getManagerId()) || myUserInfo.getLiveRoomSupperManager()) {
//                managerMenu();
//            } else {
//                // onShowTopicDetail(liveRoom.getId(), false);
//                TopicDetailsActivity.startActivity(ChatRoomActivity.this, liveRoom.getId());
//            }

        });
        videoPlayer.setLiveScreen();
    }

    private void initLiveRoom() {
        XHCustomConfig.getInstance(this).setDefConfigAudioSource(XHConstants.XHAudioSourceEnum.MIC);
        XHCustomConfig.getInstance(this).setDefConfigAudioStreamType(XHConstants.XHAudioStreamTypeEnum.STREAM_MUSIC);
        starRTCAudioManager = StarRTCAudioManager.create(this);
        starRTCAudioManager.start(new StarRTCAudioManager.AudioManagerEvents() {
            @Override
            public void onAudioDeviceChanged(StarRTCAudioManager.AudioDevice selectedAudioDevice, Set availableAudioDevices) {

            }
        });
        borderW = screenWidth;
        borderH = borderW / 3 * 4;
        liveManager = XHClient.getInstance().getLiveManager(this);
        liveManager.setRtcMediaType(XHConstants.XHRtcMediaTypeEnum.STAR_RTC_MEDIA_TYPE_VIDEO_AND_AUDIO);
        liveManager.setRecorder(new XHCameraRecorder());
        liveManager.addListener(new IXHLiveManagerListener() {
            @Override
            public void onActorJoined(String liveID, String actorID) {
                Log.i(TAG, "onActorJoined: 主播加入了 liveID：" + liveID + "actorID:" + actorID);
                addPlayer(actorID);
                if (isAnchor) {
                    return;
                }
                //第一个人加入的时候，改变观众的ui 显示直播界面
                if (mPlayerList.size() == 1) {
                    startLiveChangeUiForAudience();
                }
            }

            @Override
            public void onActorLeft(String liveID, String actorID) {
                Log.i(TAG, "onActorLeft: 主播离开了 liveID：" + liveID + "actorID:" + actorID);
                if (isLiveStarted) {
                    if (isAnchor) {
                        onStopLiveForAnchor();
                    } else {
                        onStopLiveForAudience();
                    }
                }
                deleteAllPlayer();
            }

            @Override
            public void onApplyBroadcast(String s, String s1) {

            }

            @Override
            public void onApplyResponsed(String s, XHConstants.XHLiveJoinResult xhLiveJoinResult) {

            }

            @Override
            public void onInviteBroadcast(String s, String s1) {

            }

            @Override
            public void onInviteResponsed(String s, XHConstants.XHLiveJoinResult xhLiveJoinResult) {

            }

            @Override
            public void onLiveError(String liveID, String error) {
                Log.e(TAG, "onLiveError: 直播出错。。。。。" + error);

                if (TextUtils.equals(error, "Closed")) {
                    Log.e(TAG, "onLiveError: 主播掉线了");
                    if (isLiveStarted) {
                        if (isAnchor) {
                            onStopLiveForAnchor();
                        } else {
                            onStopLiveForAudience();
                        }
                        deleteAllPlayer();
                    }
                }
            }

            @Override
            public void onMembersUpdated(int i) {

            }

            @Override
            public void onSelfKicked() {

            }

            @Override
            public void onSelfMuted(int i) {

            }

            @Override
            public void onCommandToStopPlay(String s) {

            }

            @Override
            public void onReceivedMessage(XHIMMessage xhimMessage) {

            }

            @Override
            public void onReceivePrivateMessage(XHIMMessage xhimMessage) {

            }

            @Override
            public void onReceiveRealtimeData(byte[] bytes, String s) {

            }

            @Override
            public void onPushStreamError(String s) {
                Log.e(TAG, "onPushStreamError: 推流出错: " + s);
            }
        });
        liveRoomService = IMSClientBootstrap.getInstance().getLiveRoomService();
        liveRoomService.setMessageListener(getMessageListener());

        IMSClientBootstrap.getInstance().addConnectListeners(this);
    }

    @NonNull
    private LiveRoomListener getMessageListener() {
        return new LiveRoomListener() {
            @Override
            public void onReceivedChatMessage(Message charRoomMessage) {
//                if(!isParseLiveRoom(charRoomMessage)){
//                    return;
//                }
                messageView.setData(charRoomMessage);
            }

            @Override
            public void onReceivedBarrageMessage(Message barrageMessage) {
                barrageLayout.addBarrage(barrageMessage);
                messageView.setData(barrageMessage);
            }

            @Override
            public void onUserJoin(Message message) {
                String fromId = message.getFromId();
                if (!TextUtils.equals(fromId, myUserInfo.getuId())) {//自己不从这儿添加进头像列表，否则头像数量将不正常，多了一个
                    //用户量大了，临时用户就不用显示到 头像列表
                    User audience = new User(fromId);
                    audience.setAvatar(message.getIcon());
                    audience.setUsername(message.getTitle());
                    if (message.getSubType() == Constant.IM_TYPE_JOIN_LIVE_ROOM_TEMP) {
                        audience.setType(Constant.USER_TYPE_TEMP);
                    } else if (message.getSubType() == Constant.IM_TYPE_JOIN_LIVE_ROOM) {
                        audience.setType(Constant.USER_TYPE_NORMAL);
                    }
                    avatarListView.onUserJoin(audience);
                }

                message.setContent("进来了");
                messageView.setData(message);
            }

            @Override
            public void onUserQuit(Message message) {

                String fromId = message.getFromId();
                Log.i(TAG, "onUserQuit: 有人退出直播间，，，，，，，，，，，，" + fromId);
                avatarListView.onUserExited(fromId);
                message.setContent("离开了");
                messageView.setData(message);
            }

            @Override
            public void onUserRemove(Message message) {
                String fromId = message.getFromId();
                avatarListView.onUserExited(fromId);
                Log.i(TAG, "onUserJoin: 有人被移出群，uId:" + fromId);
                message.setContent("被移出聊天室");
                messageView.setData(message);
            }

            @Override
            public void onReceivedLiveRoomPushMessage(Message liveRoomPushMessage) {
                Integer type = liveRoomPushMessage.getSubType();
                switch (type) {
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_LIVE_START: {
                        Log.i(TAG, "onReceive: 收到开始直播通知");
                        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

                        isLiveStarted = true;
                        LiveRoom liveRoom = JSONObject.parseObject(liveRoomPushMessage.getExtraData(), LiveRoom.class);
                        anchor = liveRoom.getAnchor();
                        if (isAnchor) {//避免主播方也收到开始直播的消息，过滤下
                            return;
                        }
                        avatarListView.showAnchorAvatar(liveRoom.getAnchor());
                        liveRecord = liveRoom.getLiveRecord();
                        prepareStartLive();
                        String liveId = liveRoom.getLiveId();
                        if (!TextUtils.isEmpty(liveId)) {
                            ChatRoomActivity.this.liveRoom.setLiveId(liveId);
                        }
                        watchLive();
                    }
                    break;
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_LIVE_STOP:
                        Log.i(TAG, "onReceive: 收到直播结束通知");
                        //如果是主播收到结束通知，说明是被管理员关闭了当前直播
                        //正常情况下，直播主动停止直播，是不会收到这个系统消息的
                        if (isAnchor) {
                            // TODO: 2019/7/6 是否应该显示一个对话框，发起对管理员的投诉，如何避免管理员打压异己，恶意关闭直播，，是个需要解决的问题
                            onStopLiveForAnchor();
                            ConfirmDialog dialog = new ConfirmDialog(ChatRoomActivity.this, "提示", "直播被管理员关闭");
                            dialog.show();
                        } else {
                            onStopLiveForAudience();
                        }

                        break;
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_REWARD: {
                        JSONObject info = JSONObject.parseObject(liveRoomPushMessage.getExtraData());
                        showLeftGiftView(info.getObject("reward", Reward.class));
                        int progress = info.getInteger("progress");
                        if (countDownView.isStarted()) {
                            countDownView.setProgress(progress);
                        }
//                    else {
//                        if (liveRecord != null) {
//                            showCountView(progress, liveRecord.getDuration());
//                        }
//                    }

                        break;
                    }
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_MULCT: {
                        JSONObject info = JSONObject.parseObject(liveRoomPushMessage.getExtraData());
                        int progress = info.getInteger("progress");
                        booCount++;
                        showBooView();
                        if (countDownView.isStarted()) {
                            countDownView.setProgress(progress);
                        } else if (liveRecord != null) {
                            //收到 点踩的时候，无条件触发倒计时
                            countDownView.startCount(liveRecord.getDuration(), progress);
                        }
                        break;
                    }
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_FUND_COUPON:
                        Log.i(TAG, "onReceive: 直播间收到红包" + liveRoomPushMessage.getContent());
                        Coupon coupon = JSONObject.parseObject(liveRoomPushMessage.getContent(), Coupon.class);
                        if (coupon != null) {
                            couponView.receiveCoupon(coupon);
                        }
                        break;
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_MANAGER_CHANGE: {
                        LiveRoom msgLiveRoom = JSONObject.parseObject(liveRoomPushMessage.getExtraData(), LiveRoom.class);
                        liveRoom.setManagerId(msgLiveRoom.getManagerId());
                        Log.i(TAG, "onReceive: 聊天室管理员改变");
                        User newManager = JSONObject.parseObject(liveRoomPushMessage.getContent(), User.class);
                        //刷新管理员头像
                        avatarListView.showManager(newManager);
                        //如果已经查询了主题，把主题中的管理员也一并替换掉
                        if (fullTopic != null) {
                            fullTopic.setManager(newManager);
                            fullTopic.setManagerId(newManager.getUId());
                        }
                        //通知聊天室列表刷新的管理员id
                        LiveRoom updateLiveRoom = new LiveRoom();
                        updateLiveRoom.setId(msgLiveRoom.getId());
                        updateLiveRoom.setManagerId(msgLiveRoom.getManagerId());
                        // broadcastManager.sendBroadcast(new Intent(Constant.ACTION_TOPIC_MANAGER_TRANSFER).putExtra(Constant.EXTRA_INFO_LIVE_ROOM, updateLiveRoom));
                        Message message = new Message();
                        message.setTitle("系统消息");
                        message.setContent("管理者已改变");
                        messageView.setData(message);
                        //清空已经下载的主题
                        if (fullTopic != null) {
                            fullTopic = null;
                        }
                        break;
                    }
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_MANAGER_REMOVE: {
                        Log.i(TAG, "onReceivedLiveRoomPushMessage: 管理员移除");
                        liveRoom.setManagerId(null);
                        avatarListView.onManagerRemove();
                        //清空已经下载的主题
                        if (fullTopic != null) {
                            fullTopic = null;
                        }
                        Message message = new Message();
                        message.setTitle("系统消息");
                        message.setContent("管理者空缺中...");
                        messageView.setData(message);

                        break;
                    }
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_ADVERTISEMENT_MAX_PRICE_CHANGE:
                        BigDecimal maxPriceIn24H = JSONObject.parseObject(liveRoomPushMessage.getContent(), BigDecimal.class);
                        Log.i(TAG, "onReceive: 直播间广告位当前最高价是：" + maxPriceIn24H);
                        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_ON_LIVE_ROOM_ADVERTISEMENT_PRICE_CHANGE));
                        break;
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_ADVERTISEMENT_CHANGE:
                        Log.i(TAG, "onReceive: 收到直播间广告位改变的通知" + liveRoomPushMessage.getContent());
                        advertisement = JSONObject.parseObject(liveRoomPushMessage.getContent(), Advertisement.class);
                        showAdvertisement();

                        break;

                    case Constant.LIVE_ROOM_PUSH_MESSAGE_FORBID_LIVE:
                        Log.i(TAG, "onReceive: 当前直播间禁止直播");
                        liveRoom.setStatus(Constant.LIVE_ROOM_STATUS_FORBID);
                        if (!isLiveStarted) {
                            hideLiveRoomIdleView();
                        }
                        break;
                    case Constant.LIVE_ROOM_PUSH_MESSAGE_OPEN_LIVE:
                        Log.i(TAG, "onReceive: 当前直播间开放直播");
                        liveRoom.setStatus(Constant.LIVE_ROOM_STATUS_STOPPED);
                        if (!isLiveStarted) {
                            showLiveRoomIdleView();
                        }
                        break;
                    default:
                        Log.e(TAG, "onReceivedLiveRoomPushMessage: 有消息没有处理：" + liveRoomPushMessage.toString());
                }
            }
        };
    }


    private int count = 0;

    private void watchLive() {
        String liveId = liveRoom.getLiveId();
        if (liveId == null) {
            showToast("直播id无效");
            return;
        }
        liveManager.watchLive(liveId, new IXHResultCallback() {
            @Override
            public void success(Object o) {
                Log.i(TAG, "success: 观看直播成功，，，");
                showCountView();
                avatarListView.showAnchorAvatar(liveRoom.getAnchor());
                showRewardAndMulctView();
                //startLiveChangeUiForAudience();
            }

            @Override
            public void failed(String s) {
                count++;
                Log.e(TAG, "failed: 观看直播失败，..." + s + "重连尝试第" + count + "次");
                if (count <= 4) {
                    handler.postDelayed(watchLiveRunnable, 1000);
                } else {
                    //观看直播失败，显示出直播按键

                    showLiveRoomIdleView();
                }
            }
        });
    }

    private void initClickListener() {
        iv_liveRoomIdle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //避免重复点击
                if (ClickUtil.isFastClick()) return;
                if (!Helper.getInstance().isNetworkConnected()) {
                    showToast_v1(getString(R.string.network_anomalies));
                    return;
                }

                if (Utils.isTempUser(myUserInfo)) {
                    hideSoftKeyboard();
                    LoginActivity.startActivity(ChatRoomActivity.this, "启动焦点需要先登录");
                    return;
                }
                checkPermission();
            }
        });
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.removeCallbacks(countDownRunnable);
                startLive();
            }
        });
        iv_voiceSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iv_voiceSwitch.isSelected()) {
                    iv_voiceSwitch.setSelected(false);
                    //mRtcEngine.muteLocalAudioStream(false);
                    liveManager.setAudioEnable(true);

                } else {
                    iv_voiceSwitch.setSelected(true);
                    // mRtcEngine.muteLocalAudioStream(true);
                    liveManager.setAudioEnable(false);
                }
            }
        });
        iv_cameraSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //切换摄像头
                // mRtcEngine.switchCamera();
                liveManager.switchCamera();
                if (iv_cameraSwitch.isSelected()) {
                    iv_cameraSwitch.setSelected(false);
                } else {
                    iv_cameraSwitch.setSelected(true);
                }
            }
        });

        iv_lightSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iv_lightSwitch.isSelected()) {
                    iv_lightSwitch.setSelected(false);
                    //mRtcEngine.setCameraTorchOn(false);


                } else {
                    iv_lightSwitch.setSelected(true);
                    //  mRtcEngine.setCameraTorchOn(true);

                }
            }
        });
        //广告位点击事件监听，如果在视频播放完成之前就能点击的话，还需要监听 surface_container
        videoPlayer.thumbImageView.setOnClickListener(v -> {
            if (advertisement == null) {
                return;
            }
            if (advertisement.getForwardTopicId() != null) {
                onShowTopicDetail(liveRoom.getId(), true);
            } else if (advertisement.getForwardUrl() != null) {
                startActivity(new Intent(ChatRoomActivity.this, ExternalUrlActivity.class).putExtra("forward_url", advertisement.getForwardUrl()));
            }
        });

        coverView.setOnClickListener(v -> {
            if (advertisement == null) {
                return;
            }
            if (advertisement.getForwardTopicId() != null) {
                onShowTopicDetail(liveRoom.getId(), true);
            } else if (advertisement.getForwardUrl() != null) {
                startActivity(new Intent(ChatRoomActivity.this, ExternalUrlActivity.class).putExtra("forward_url", advertisement.getForwardUrl()));
            }
        });
    }


    private void prepareLive(String liveId) {

        progressBar.setVisibility(View.VISIBLE);
        LiveRoom updateLiveRoom = new LiveRoom();
        updateLiveRoom.setId(liveRoom.getId());
        updateLiveRoom.setLiveId(liveId);
        if (liveRecord != null) {//如果当前直播记录不是空的，说明是上一个直播掉线了，没有正常退出直播，这样的情况下，携带上上一次的直播记录id ，后续需要判断是否和上一厂直播id 相同，相同才允许开始直播
            updateLiveRoom.setrId(liveRecord.getId());
        }
        isAnchor = true;
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .startLive(updateLiveRoom)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "开始直播错误:" + response.code());
                            isAnchor = false;
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "开始直播错误:" + result.getMsg());
                            isAnchor = false;
                            switch (result.getStatus()) {

                                case Constant.LIVE_ROOM_HAD_STARTED:
                                    showToast(iv_liveRoomIdle, "手慢了一点，别人已经开始直播了");
                                    break;
                                case Constant.LIVE_STATUS_ERROR:
                                    showToast(iv_liveRoomIdle, "当前焦点状态有误，不能开启直播");
                                    break;
                            }

                            return;
                        }

                        Log.d(TAG, "开始直播:更新服务端完成");


                        //设置角色为主播，开始直播is
                        JSONObject data = (JSONObject) result.getData();
                        liveRecord = data.toJavaObject(LiveRecord.class);
                        //保持屏幕常量
                        // getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//                        getWindow().addFlags(
//                                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
//                                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
//                                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
                        //发送通知信息到直播间，开始直播
                        //通知直接走服务端了
                        // notifyStartLive(liveRecord);


                        // countDownView.startCount(liveRecord.getDuration(), liveRecord.getDuration());
                        //setClientRole(Constants.CLIENT_ROLE_BROADCASTER);
                        //暂停发送本地视频流
                        //  mRtcEngine.muteLocalAudioStream(true);
                        // mRtcEngine.muteLocalVideoStream(true);
                        //开始5s倒计时,倒计时结束都没有手动点开始，自动开始
                        countDown = COUNTDOWN_START_INDEX;
                        avatarListView.showAnchorAvatar(myUserInfo);
                        //因为没有starRTC没有预览功能
                        // 那就直接开始
                        startLive();
                        anchor = myUserInfo;
                        //  handler.post(countDownRunnable);
//                        countDownThread = new Thread() {
//                            public void run() {
//                                int i = COUNTDOWN_START_INDEX;
//                                do {
//                                    final int finalI = i;
//                                    runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//
//                                            handleUpdateCountdown(finalI);
//                                        }
//                                    });
//                                    i--;
//                                    try {
//                                        Thread.sleep(COUNTDOWN_DELAY);
//                                    } catch (InterruptedException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                                while (!isLiveStarted && i >= COUNTDOWN_END_INDEX);
//                            }
//                        };
//                        countDownThread.start();


                        // if (surfaceViewLocal == null) {
                        //设置本地视频
                        //void attachPlayerView(String userID,StarPlayer player,Boolean isBig);


                        //    }
//                                        else {
//                                            //判断容器中的是否是本地视频view,如果不是，则清空容器，重新添加本地视频view
//                                            if (rl_videoContainer.getChildCount() != 0 && !TextUtils.equals((String) rl_videoContainer.getChildAt(0).getTag(), "local")) {
//                                                rl_videoContainer.removeAllViews();
//                                                rl_videoContainer.addView(surfaceViewLocal);
//                                            }
//                                        }
                        //更改ui 把直播需要的按键，显示出来，隐藏coverView等
                        startLiveChangeUIForAnchor();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        isAnchor = false;
                        ChatRoomActivity.this.showToast_v1(getString(R.string.system_busy));
                    }
                });
    }

    /**
     * 如果在直播中，就退出直播，如果没有，就退出频道
     */
    @OnClick(R.id.img_bt_close)
    void close() {

        if (isAnchor) {

            ConfirmDialog dialog = new ConfirmDialog(this, "提醒", "正在直播中，确定退出吗？", true);
            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    stopLiveToService();
                }
            });
            dialog.show();
        } else {
            if (isLiveStarted) {
                Log.d(TAG, "close: 直播进行中，退出直播间先调用  liveManager.leaveLive(");

                liveManager.leaveLive(new IXHResultCallback() {
                    @Override
                    public void success(Object o) {
                        Log.i(TAG, "success: 离开直播间");
                        finish();
                    }

                    @Override
                    public void failed(String s) {
                        Log.e(TAG, "failed: 离开直播间出错" + s);
                        finish();
                    }
                });
            } else {
                finish();
            }
            //  finish();
        }
    }

    private void stopLiveToService() {
        if (!Helper.getInstance().isNetworkConnected()) {
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        LiveRoom newLiveRoom = new LiveRoom();
        newLiveRoom.setId(liveRoom.getId());
        newLiveRoom.setrId(liveRecord.getId());
        // newLiveRoom.setManagerId(liveRoom.getManagerId());
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .stopLive(newLiveRoom)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "停止直播出错:" + response.code());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "停止直播出错:" + result.getMsg());
                            if (result.getStatus() == Constant.TOKEN_INVALID) {
                                showToast(iv_liveRoomIdle, getString(R.string.login_expire));
                            }
                            return;
                        }


                        LiveRecord liveRecord = null;
                        //服务端直接通知了
                        //  notifyStopLive();
                        if (result.getData() != null) {
                            JSONObject data = (JSONObject) result.getData();
                            Log.i(TAG, "停止直播完成" + data.toJSONString());
                            liveRecord = data.toJavaObject(LiveRecord.class);
                        } else {
                            Log.i(TAG, "停止直播完成,没有任何赏罚 无须结算");
                            liveRecord = new LiveRecord();
                        }
                        liveRecord.setAudienceSize(avatarListView.getAudienceSize());
                        //补全id.从服务端传回的liveRecord 没有ID
                        String id = ChatRoomActivity.this.liveRecord.getId();
                        liveRecord.setId(id);
                        liveRecord.setrId(liveRoom.getId());
                        //显示结算 对话框
                        StopLiveDialog stopLiveDialog = new StopLiveDialog(ChatRoomActivity.this, liveRecord);
                        stopLiveDialog.setCanceledOnTouchOutside(false);
                        stopLiveDialog.setCancelable(false);
                        stopLiveDialog.show();

                        onStopLiveForAnchor();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    private void managerStopLive() {
        if (!Helper.getInstance().isNetworkConnected()) {
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        LiveRoom newLiveRoom = new LiveRoom();
        newLiveRoom.setId(liveRoom.getId());
        if (liveRecord != null) {
            newLiveRoom.setrId(liveRecord.getId());
        }
        newLiveRoom.setanchorId(liveRoom.getanchorId());
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .managerStopLive(newLiveRoom)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "停止直播出错:" + response.code());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "停止直播出错:" + result.getMsg());
                            if (result.getStatus() == Constant.TOKEN_INVALID) {
                                showToast(iv_liveRoomIdle, getString(R.string.login_expire));
                            }
                            return;
                        }
                        Log.i(TAG, "管理员停止直播完");

                        onStopLiveForAudience();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    /**
     * 主播停止直播后调用
     */
    private void onStopLiveForAnchor() {
        liveManager.leaveLive(new IXHResultCallback() {
            @Override
            public void success(Object o) {

                Log.i(TAG, "success: 停止推流完成");
            }

            @Override
            public void failed(String s) {
                Log.e(TAG, "failed: 停止推流失败" + s);

            }
        });
        //清除屏幕常亮
        // getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//        getWindow().clearFlags(
//                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
//                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
//                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        isAnchor = false;
        isLiveStarted = false;
        //mRtcEngine.muteLocalVideoStream(true);
        //setClientRole(Constants.CLIENT_ROLE_AUDIENCE);
        //  removeVideoView();
        avatarListView.hideAnchorAvatar();
        countDownView.stopCount();
        deletePlayer(myUserInfo.getuId());
        stopLiveChangeUIForAnchor();
    }

    private synchronized void onStopLiveForAudience() {
        isLiveStarted = false;
        //audienceList.add(anchor);
        liveRecord = null;
        anchor = null;
        stopLiveChangeUiForAudience();
        if (goodsList != null) {
            goodsList.clear();
        }
        booCount = 0;//停止的时候，重置点踩的数量
        avatarListView.hideAnchorAvatar();
        //  getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//        getWindow().clearFlags(
//                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
//                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
//                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        //清理播放器
        rl_videoContainer.removeAllViews();
        mPlayerList.clear();
    }


    @OnClick(R.id.present_image)
    void onPresentImageClick() {

        if (liveRecord == null || liveRoom == null) {
            return;
        }
        presentDialog = new PresentDialog(this, liveRecord, liveRoom.getId(), avatarListView.getAudienceSize(), this, presents);
        presentDialog.show();
    }


    @OnClick(R.id.iv_pass)
    void onPassImageClick() {

//        final double money = 0.1;
//
//        new PayUtils(money, ChatRoomActivity.this, new PayUtils.InteractionListener() {
//            @Override
//            public void onPrepareComplete(String payPassword) {
//                mulct(money, payPassword);
//            }
//        });
        if (liveRecord == null || liveRoom == null) {
            return;
        }
        mulctDialog = new MulctDialog(this, liveRecord, liveRoom.getId(), avatarListView.getAudienceSize(), this, mulctItemList);
        mulctDialog.show();

    }


    @OnClick(R.id.iv_offer)
    void onOfferImageClick() {
//        OfferDialogNew offerDialogNew = new OfferDialogNew(this,dm.widthPixels);
//        offerDialogNew.show();

        OfferDialog offerDialog = OfferDialog.newInstance(100);
        offerDialog.show(getSupportFragmentManager(), "OfferDialog");
        offerDialog.setOnOfferClickListener(new OfferDialog.OnOfferClickListener() {
            @Override
            public void offerClick(final Integer offer) {
                Topic updateGoode = new Topic();

            }
        });
    }

    @Override
    public void onPresentSendSuccess(final Reward reward, Integer progress) {

        //后端并没有返回打赏者的用户信息，所以需要在这儿添加
        reward.setUser(myUserInfo);
        showLeftGiftView(reward);
        if (countDownView.isStarted()) {
            countDownView.setProgress(progress);
        }
//        else {
//            if (liveRecord != null) {
//                showCountView(progress, liveRecord.getDuration());
//            }
//        }
        //打赏成功的时候，服务端会通知到 直播间里面
        // notifyReward(reward, progress);

        /**
         * 本地送出礼物不走服务端直接显示 启用此处需要同时修改LiveBaseActivity的
         *   initChannelListener()方法中的Constant.LIVE_ROOM_PUSH_MESSAGE_RECEIVED_REWARD情况
         */


//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {

//
//            }
//        });
    }

    @Override
    public void onMulctSuccess(Mulct mulct, Integer progress) {
        booCount++;
        showBooView();
        if (countDownView.isStarted()) {
            countDownView.setProgress(progress);
        } else {
            if (liveRecord != null) {
                countDownView.startCount(liveRecord.getDuration(), progress);
            }
        }
    }

    @Override
    public void showToast(String message) {
        super.showToast(message);
    }

    /**
     * 进入直播间，查询直播间状态
     */
    private void loadData() {
        if (!Helper.getInstance().isNetworkConnected()) {
            this.showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .queryLiveRoom(liveRoom.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        if (result.getData() == null) {
                            Log.e(TAG, "onResponse: 返回数据为空");
                            return;
                        }
                        JSONObject object = (JSONObject) result.getData();
                        Log.i(TAG, "onResponse: " + object.toJSONString());
                        liveRoom = object.toJavaObject(LiveRoom.class);
                        avatarListView.init(liveRoom);//需要在新返回的 liveRoom 信息后，才去初始化头像列表，因为在这之前的liveRoom 可能 过期的
//                        List<String> memberIdList = liveRoom.getMemberIdList();
//                        //如果是在直播中，主播不为空，把主播id 从成员列表中清除
//                        if (liveRoom.getAnchor() != null && memberIdList != null && memberIdList.size() != 0) {
//                            memberIdList.remove(liveRoom.getAnchor().getuId());
//                        }
                        couponView.init(liveRoom);
                        advertisement = liveRoom.getAdvertisement();
                        showAdvertisement();
                        Integer status = liveRoom.getStatus();
                        if (status == null) {
                            return;
                        }
                        switch (status) {
                            case Constant.LIVE_ROOM_STATUS_FORBID:
                                forbidLiveChangeUiForAudience();
                                break;
                            case Constant.LIVE_ROOM_STATUS_STARTED:
                                isLiveStarted = true;
                                //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                                anchor = liveRoom.getAnchor();
                                liveRecord = liveRoom.getLiveRecord();
//                                showCountView();
//                                avatarListView.showAnchorAvatar(liveRoom.getAnchor());
//                                showRewardAndMulctView();
//                                startLiveChangeUiForAudience();
                                hideLiveRoomIdleView();
                                watchLive();

                                if (anchor != null) {
                                    refreshGoodsList(anchor.getuId());
                                }
                                break;
                            case Constant.LIVE_ROOM_STATUS_STOPPED:
                                stopLiveChangeUiForAudience();
                                break;

                            case Constant.LIVE_ROOM_STATUS_AUCTION:

                                //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                                liveRecord = liveRoom.getLiveRecord();
                                showCountView();
                                anchor = liveRoom.getAnchor();
                                bindGoods = object.getObject("bindGoods", Topic.class);
                                changeUiForStartAuction();
                                watchLive();
                                avatarListView.showAnchorAvatar(liveRoom.getAnchor());

                                refreshGoodsList(anchor.getuId());
                                break;
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    /**
     * 根据直播记录和是否有 点踩
     * 判断是否显示直播倒计时
     */
    private void showCountView() {

        if (liveRecord != null && liveRecord.getMulct() != null) {
            countDownView.startCount(liveRecord.getDuration(), liveRecord.getProgress());
        }
    }


    /**
     * 开启发送视频流
     */
    private void startLive() {
        isLiveStarted = true;
        // tv_countdownView.getAnimation().cancel();
        if (tv_countdownView.getVisibility() == View.VISIBLE) {
            tv_countdownView.setVisibility(View.GONE);
        }
        startBtn.setVisibility(View.GONE);
        bottomBar.setVisibility(View.VISIBLE);
        //发送本地视频流
        //mRtcEngine.muteLocalAudioStream(false);
        // mRtcEngine.muteLocalVideoStream(false);

        liveManager.startLive(liveRoom.getLiveId(), new IXHResultCallback() {
            @Override
            public void success(Object o) {
                //显示本地视频
                // addPlayer(myUserInfo.getuId());
                Log.i(TAG, "success: 开始直播完成");
            }

            @Override
            public void failed(String s) {
                Log.e(TAG, "failed: 开始直播失败" + s);
            }
        });
    }

    /**
     * 开始直播，主播端调整UI
     */
    private void startLiveChangeUIForAnchor() {
        //判断输入框是否是显示状态，如果是，则隐藏，因为进入主播状态后，用的着输入框的可能比较小
        if (messageView.isInputViewDisplay()) {
            messageView.setShowInputView(false);
        } else {
            // bottomBar.setVisibility(View.GONE);
        }
        iv_liveRoomIdle.setVisibility(View.INVISIBLE);
        ll_cover.setVisibility(View.GONE);
        //没有预览，直接开始，不用显示 startBtn
        //startBtn.setVisibility(View.VISIBLE);
        // TODO: 2019/7/5 以后解决闪光灯问题，暂时直接隐藏掉，，，
        //iv_lightSwitch.setVisibility(View.VISIBLE);
        iv_voiceSwitch.setVisibility(View.VISIBLE);
        if (iv_voiceSwitch.isSelected()) {
            iv_voiceSwitch.setSelected(false);
        }
        iv_cameraSwitch.setVisibility(View.VISIBLE);
        checkAndStopVideo();
        setMessageViewLayoutToSmall();
    }

    /**
     * 停止直播，主播端调整UI
     */
    private void stopLiveChangeUIForAnchor() {
        if (messageView.isInputViewDisplay()) {
            messageView.setShowInputView(false);
        }
        showLiveRoomIdleView();
        ll_cover.setVisibility(View.VISIBLE);
        iv_lightSwitch.setVisibility(View.GONE);
        iv_voiceSwitch.setVisibility(View.GONE);
        iv_cameraSwitch.setVisibility(View.GONE);
        if (startBtn.isShown()) {
            startBtn.setVisibility(View.GONE);
        }
        if (!bottomBar.isShown()) {
            bottomBar.setVisibility(View.VISIBLE);
        }
        if (tv_countdownView.isShown()) {
            tv_countdownView.setVisibility(View.INVISIBLE);
        }
        checkAndStartVideo();
        setMessageViewLayoutToBig();
    }

    /**
     * 开始直播的时候，让MessageView 变小，不要挡住直播画面
     */
    private void setMessageViewLayoutToSmall() {
        RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) (msgViewHeight * dm.density));
        param.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        messageView.setLayoutParams(param);
    }

    /**
     * 没有直播的时候，让MessageView 变大，能显示更多观众发的信息
     */
    private void setMessageViewLayoutToBig() {
        RelativeLayout.LayoutParams param2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        param2.addRule(RelativeLayout.BELOW, R.id.avatar_list_view);
        messageView.setLayoutParams(param2);
    }


    private void readyLiveChangeUiForAudience() {
        //如果在软键盘打开的情况下，显示远程视频view,view 会被缩小，只有隐藏掉软件盘
        if (messageView.isInputViewDisplay()) {
            messageView.setShowInputView(false);
            bottomBar.setVisibility(View.VISIBLE);
        }
        // hideLiveRoomIdleView();
    }

    private void hideLiveRoomIdleView() {
        iv_liveRoomIdle.setVisibility(View.INVISIBLE);

    }

    /**
     * 显示直播按键
     */
    private void showLiveRoomIdleView() {
        Integer status = liveRoom.getStatus();
        if (status != null && status != Constant.LIVE_ROOM_STATUS_FORBID) {
            iv_liveRoomIdle.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 开始直播，观众端调整ui
     */
    private void startLiveChangeUiForAudience() {

        isLiveStarted = true;
        iv_offer.setVisibility(View.GONE);
        ll_cover.setVisibility(View.GONE);

        checkAndStopVideo();

        setMessageViewLayoutToSmall();
    }


    private void showRewardAndMulctView() {
        iv_present.setVisibility(View.VISIBLE);
        iv_pass.setVisibility(View.VISIBLE);
    }

    /**
     * 禁止 直播
     */
    private void forbidLiveChangeUiForAudience() {
        iv_offer.setVisibility(View.GONE);
        iv_present.setVisibility(View.GONE);
        iv_pass.setVisibility(View.GONE);
        tv_bindGoodsName.setVisibility(View.INVISIBLE);
        offerView.setVisibility(View.INVISIBLE);
        tv_offerAmount.setVisibility(View.INVISIBLE);
        countDownView.stopCount();
        ll_cover.setVisibility(View.VISIBLE);
        setMessageViewLayoutToBig();
        //停止直播的时候情况掉打赏和出价的列表，避免出现直播停止了，还一直在显示上一场直播观众的打赏和出价
        rewardList.clear();
        ordersList.clear();
        if (presentDialog != null) {
            presentDialog.dismiss();
        }
        if (mulctDialog != null) {
            mulctDialog.dismiss();
        }
    }

    /**
     * 停止直播，观众端调整UI
     */
    private void stopLiveChangeUiForAudience() {
        showLiveRoomIdleView();
//直播停止的时候，如果有广告位，或者直播间封面是 视频，那么开始播放
        checkAndStartVideo();
        forbidLiveChangeUiForAudience();
    }

    private void checkAndStopVideo() {
        if (!TextUtils.isEmpty(liveRoom.getVideo()) || (advertisement != null && !TextUtils.isEmpty(advertisement.getVideo()))) {
            videoPlayer.reset();
        }
    }

    private void checkAndStartVideo() {
        if (!TextUtils.isEmpty(liveRoom.getVideo()) || (advertisement != null && !TextUtils.isEmpty(advertisement.getVideo()))) {
            if (videoPlayer.state != Jzvd.STATE_PLAYING) {
                videoPlayer.startVideo();
            }
        }
    }

    /**
     * 进入拍卖状态，调整UI
     */
    private void changeUiForStartAuction() {
        if (!isLiveStarted) {
            if (anchor != null) {
                // avatarListView.showAnchorAvatar();
            }
            iv_liveRoomIdle.setVisibility(View.INVISIBLE);
        }
        tv_bindGoodsName.setText(bindGoods.getTitle());
        iv_offer.setVisibility(View.VISIBLE);
        tv_bindGoodsName.setVisibility(View.VISIBLE);
        setMessageViewLayoutToSmall();
    }

    public void handleUpdateCountdown() {
        if (tv_countdownView != null) {
            tv_countdownView.setVisibility(View.VISIBLE);
            tv_countdownView.setText(String.format("%d", countDown));

            ScaleAnimation scaleAnimation =
                    new ScaleAnimation(1.0f, 0f, 1.0f, 0f, Animation.RELATIVE_TO_SELF, 0.5f,
                            Animation.RELATIVE_TO_SELF, 0.5f);
            scaleAnimation.setDuration(COUNTDOWN_DELAY);
            scaleAnimation.setFillAfter(false);
            scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    tv_countdownView.setVisibility(View.GONE);
                    //startBtn.setVisibility(View.GONE);

//                    if (count == COUNTDOWN_END_INDEX) {
//                        // showToast(startBtn, "自动退出直播");
//                        //close();
//                        //倒计时结束，自动开启推流，避免一直占用着直播间，观众端又看不到画面
//                        if (!isLiveStarted) {
//                            runOnUiThread(() -> startLive());
//                        }
//                    }
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            tv_countdownView.startAnimation(scaleAnimation);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isMessageListInited)
            messageView.refresh();
        //  EaseUI.getInstance().pushActivity(this);
        // register the event listener when enter the foreground

//        if (realTimeData.isConnected()) {
//            realTimeData.subRowUpdate("LiveRoom", liveRoom.getObjectId());
//        }
        JzvdStd.goOnPlayOnResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        //mVideoView.onPause();
//        if (realTimeData.isConnected()) {
//            realTimeData.unsubRowUpdate("LiveRoom", liveRoom.getObjectId());
//        }
        JzvdStd.goOnPlayOnPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        // unregister this event listener when this activity enters the
        // background


        // 把此activity 从foreground activity 列表里移除
        //  EaseUI.getInstance().popActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // mRtcEngine.leaveChannel();
        // RtcEngine.destroy();

        JzvdStd.resetAllVideos();
        if (liveRoomService != null) {
            liveRoomService.quitLiveRoom();
            liveRoomService.clear();//不能把清理工作放在 退出直播间里面，因为用户切换的时候，需要使用 回调
        }
        if (starRTCAudioManager != null) {
            starRTCAudioManager.stop();
        }

        broadcastManager.unregisterReceiver(broadcastReceiver);
        handler.removeCallbacksAndMessages(null);
        countDownView.clear();
        PermissionsUtils.getInstance().clear();
        IMSClientBootstrap.getInstance().removeConnectListener(this);
    }


    @Override
    public void onBackPressed() {
        close();
    }

    @Override
    public void onTimeOut() {
        if (isAnchor) {
            stopLiveToService();
        }
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_TOPIC_MANAGER_TRANSFER);
        intentFilter.addAction(Constant.ACTION_TOPIC_MANAGER_REMOVE);
        intentFilter.addAction(Constant.ACTION_TOPIC_EDIT_CHANGED);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action) {
                    //刷新动态发布的主题信息
                    case Constant.ACTION_TOPIC_EDIT_CHANGED:
                        fullTopic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                        if (fullTopic != null) {

                            boolean isUpdated = false;
                            List<String> pictures = fullTopic.getPictures();
                            if (pictures.size() != 0 && !TextUtils.equals(pictures.get(0), liveRoom.getCover())) {
                                liveRoom.setCover(pictures.get(0));
                                isUpdated = true;
                            }
                            if (!TextUtils.equals(fullTopic.getVideo(), liveRoom.getVideo())) {
                                liveRoom.setVideo(fullTopic.getVideo());
                                isUpdated = true;
                            }
                            if (isUpdated) {
                                showCover();
                                ChatRoomActivity.this.setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_LIVE_ROOM, liveRoom));
                            }
                        }
                        break;

                    case Constant.ACTION_TOPIC_MANAGER_REMOVE://管理员自己放弃管理员权限后，直播间处于管理员缺失状态，不再显示管理员
                        liveRoom.setManagerId(null);
                        avatarListView.onManagerRemove();
                        break;
                    case Constant.ACTION_TOPIC_MANAGER_TRANSFER://管理员移交后，刷新直播间管理员头像
                        Topic updateTopic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                        if (updateTopic == null) {
                            return;
                        }
                        liveRoom.setManagerId(updateTopic.getManagerId());
                        avatarListView.showManager(updateTopic.getManager());

                        break;

                }


            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_EDIT_TOPIC:
                fullTopic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                if (fullTopic == null) {
                    return;
                }
                List<String> pictures = fullTopic.getPictures();
                if (pictures != null && pictures.size() != 0) {
                    liveRoom.setCover(pictures.get(0));
                }
                liveRoom.setVideo(fullTopic.getVideo());
                liveRoom.setTitle(fullTopic.getTitle());
                showCover();
                setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_LIVE_ROOM, liveRoom));
        }
    }

    public void onShowTopicDetail(final String topicId, boolean isAdvertisement) {
        if (isAdvertisement && advertisementTopic != null) {
            //创建聊天室的时候
            ((Activity) context).startActivityForResult(new Intent(context, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, advertisementTopic), TopicRecordActivity.REQUEST_CODE_EDIT_TOPIC);
            return;

        } else if (fullTopic != null) {
            if (fullTopic.getStatus() == Constant.TOPIC_STATUS_WAIT_VERIFY) {
                showToast("待审核状态,不能使用");
                return;
            }
            ((Activity) context).startActivityForResult(new Intent(context, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, fullTopic), TopicRecordActivity.REQUEST_CODE_EDIT_TOPIC);
            return;

        }

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .getTopicFromMysql_v2(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() && result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        CommonResult body = response.body();
                        JSONObject data = (JSONObject) body.getData();
                        if (data == null) {
                            return;
                        }
                        Log.d(TAG, "onResponse: 查询topic完成：" + data);
                        if (isAdvertisement) {
                            advertisementTopic = data.getObject("topic", Topic.class);//es get方法返回的对象没有id
                            if (advertisementTopic == null) {

                                Log.e(TAG, "onResponse: advertisementTopic为空，，，，，，，，，，，，，，，，，，，，");
                                return;
                            }
                            advertisementTopic.setId(topicId);
                            ((Activity) context).startActivityForResult(new Intent(context, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, advertisementTopic), TopicRecordActivity.REQUEST_CODE_EDIT_TOPIC);
                        } else {
                            fullTopic = data.getObject("topic", Topic.class);//es get方法返回的对象没有id
                            if (fullTopic == null) {
                                Log.e(TAG, "onResponse: fullTopic 为空，，，，，，，，，，，，，，，，，，，，，，");
                                return;
                            }
                            fullTopic.setId(topicId);
                            if (fullTopic.getStatus() == Constant.TOPIC_STATUS_WAIT_VERIFY) {
                                showToast("待审核状态,不能使用");
                                return;
                            }
                            ((Activity) context).startActivityForResult(new Intent(context, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, fullTopic), TopicRecordActivity.REQUEST_CODE_EDIT_TOPIC);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        showToast(getString(R.string.system_busy));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    @Override
    public void onSendCouponComplete(Coupon coupon) {
        // notifySendMultipleCoinCoupon(coupon);
    }

    @Override
    public void onReceiveCouponComplete(Coupon coupon) {

    }

    @Override
    public void onCouponStatusChange(Coupon coupon) {

    }


    public void onAnchorJoin() {
        //查询直播间的信息
        // loadData(false); 现在更从这儿去查询，根据服务端推送的直播开始的消息中，拿到直播开始相关数据了，
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                readyLiveChangeUiForAudience();
            }
        });
    }


    public void prepareStartLive() {
        hideLiveRoomIdleView();
        // countDownView.startCount(liveRecord.getDuration(), liveRecord.getDuration());
        // showRewardAndMulctView();
        refreshGoodsList(anchor.getuId());


    }


    public void onAnchorLeave() {
        resetLiveRoom();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //   stopLiveChangeUiForAudience();
                //当主播关闭直播的时候，删除远程视频view，
                removeVideoView();
            }
        });
    }


    private void addPlayer(String addUserID) {
        for (ViewPosition viewPosition : mPlayerList) {
            if (TextUtils.equals(viewPosition.getUserId(), addUserID)) {
                return;
            }
        }

        ViewPosition newOne = new ViewPosition();
        newOne.setUserId(addUserID);
        StarPlayer player = new StarPlayer(this);
        newOne.setVideoPlayer(player);
        mPlayerList.add(newOne);
        rl_videoContainer.addView(player);
//        CircularCoverView coverView = new CircularCoverView(this);
//        coverView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//        coverView.setCoverColor(Color.BLACK);
//        coverView.setRadians(35, 35, 35, 35,10);
        //player.addView(coverView);
        player.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeLayout(v);
            }
        });
        resetLayout();
        player.setZOrderMediaOverlay(true);
        player.setScalType(StarPlayerScaleType.DRAW_TYPE_CENTER);

        if (mPlayerList.size() == 1) {
            liveManager.attachPlayerView(addUserID, player, true);
        } else {
            liveManager.attachPlayerView(addUserID, player, false);
        }
    }

    private boolean isRuning = false;

    private void resetLayout() {
        //不用判断是否是竖屏的，因为目前限制了 屏幕只能是竖屏
        //if(isPortrait){
        switch (mPlayerList.size()) {
            case 1: {
                StarPlayer player = mPlayerList.get(0).getVideoPlayer();
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                player.setLayoutParams(lp);
                player.setY(0);
                player.setX(0);
                break;
            }
            case 2:
            case 3:
            case 4: {
                for (int i = 0; i < mPlayerList.size(); i++) {
                    if (i == 0) {
                        StarPlayer player = mPlayerList.get(i).getVideoPlayer();
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW / 3 * 2, borderH);
                        player.setLayoutParams(lp);
                        player.setY(0);
                        player.setX(0);
                    } else {
                        StarPlayer player = mPlayerList.get(i).getVideoPlayer();
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW / 3, borderH / 3);
                        player.setLayoutParams(lp);
                        player.setY((i - 1) * borderH / 3);
                        player.setX(borderW / 3 * 2);
                    }
                }
                break;
            }
            case 5:
            case 6:
            case 7: {
                for (int i = 0; i < mPlayerList.size(); i++) {
                    if (i == 0) {
                        StarPlayer player = mPlayerList.get(i).getVideoPlayer();
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW - borderW / 3, borderH - borderH / 4);
                        player.setLayoutParams(lp);
                    } else if (i > 0 && i < 3) {
                        StarPlayer player = mPlayerList.get(i).getVideoPlayer();
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW / 3, borderH / 4);
                        player.setLayoutParams(lp);
                        player.setX(borderW - borderW / 3);
                        player.setY((i - 1) * borderH / 4);
                    } else {
                        StarPlayer player = mPlayerList.get(i).getVideoPlayer();
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW / 3, borderH / 4);
                        player.setLayoutParams(lp);
                        player.setX((i - 3) * borderW / 3);
                        player.setY(borderH - borderH / 4);
                    }
                }
                break;
            }
        }
//        }else{
//            switch (mPlayerList.size()){
//                case 1:{
//                    StarPlayer player = mPlayerList.get(0).getVideoPlayer();
//                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW,borderH);
//                    player.setLayoutParams(lp);
//                    player.setY(0);
//                    player.setX(0);
//                    break;
//                }
//                case 2:
//                case 3:
//                case 4:
//                {
//                    for(int i = 0;i<mPlayerList.size();i++){
//                        if(i==0){
//                            StarPlayer player = mPlayerList.get(i).getVideoPlayer();
//                            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW/4*3,borderH);
//                            player.setLayoutParams(lp);
//                            player.setY(0);
//                            player.setX(0);
//                        }else{
//                            StarPlayer player = mPlayerList.get(i).getVideoPlayer();
//                            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW/4,borderH/3);
//                            player.setLayoutParams(lp);
//                            player.setY((i-1)*borderH/3);
//                            player.setX(borderW/4*3);
//                            player.setScalType(StarPlayerScaleType.DRAW_TYPE_TOTAL_GRAPH);
//                        }
//                    }
//                    break;
//                }
//                case 5:
//                case 6:
//                case 7:{
//                    for(int i = 0;i<mPlayerList.size();i++){
//                        if(i==0){
//                            StarPlayer player = mPlayerList.get(i).getVideoPlayer();
//                            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW/4*2,borderH);
//                            player.setLayoutParams(lp);
//                            player.setY(0);
//                            player.setX(0);
//                        }else if(i>0&&i<3){
//                            StarPlayer player = mPlayerList.get(i).getVideoPlayer();
//                            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW/4,borderH/3);
//                            player.setLayoutParams(lp);
//                            player.setY((i-1)*borderH/3);
//                            player.setX(borderW/4*2);
//                        }else{
//                            StarPlayer player = mPlayerList.get(i).getVideoPlayer();
//                            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(borderW/4,borderH/3);
//                            player.setLayoutParams(lp);
//                            player.setY((i-3)*borderH/3);
//                            player.setX(borderW/4*3);
//                        }
//                    }
//                    break;
//                }
//            }
//        }


    }

    private void changeLayout(View v) {
        if (isRuning) return;
        if (v == mPlayerList.get(0).getVideoPlayer()) return;
        ViewPosition clickPlayer = null;
        int clickIndex = 0;
        for (int i = 0; i < mPlayerList.size(); i++) {
            if (mPlayerList.get(i).getVideoPlayer() == v) {
                clickIndex = i;
                clickPlayer = mPlayerList.remove(i);
                liveManager.changeToBig(clickPlayer.getUserId());
                break;
            }
        }
        final ViewPosition mainPlayer = mPlayerList.remove(0);
        liveManager.changeToSmall(mainPlayer.getUserId());
        mPlayerList.remove(clickPlayer);
        mPlayerList.add(0, clickPlayer);
        mPlayerList.add(clickIndex, mainPlayer);

        final ViewPosition finalClickPlayer = clickPlayer;
        startAnimation(finalClickPlayer.getVideoPlayer(), mainPlayer.getVideoPlayer());
    }

    private void startAnimation(final StarPlayer clickPlayer, final StarPlayer mainPlayer) {
        final float clickStartW = clickPlayer.getWidth();
        final float clickStartH = clickPlayer.getHeight();
        final float clickEndW = mainPlayer.getWidth();
        final float clickEndH = mainPlayer.getHeight();
        final float mainStartW = mainPlayer.getWidth();
        final float mainStartH = mainPlayer.getHeight();
        final float mainEndW = clickPlayer.getWidth();
        final float mainEndH = clickPlayer.getHeight();

        final float clickStartX = clickPlayer.getX();
        final float clickStartY = clickPlayer.getY();
        final float clickEndX = mainPlayer.getX();
        final float clickEndY = mainPlayer.getY();
        final float mainStartX = mainPlayer.getX();
        final float mainStartY = mainPlayer.getY();
        final float mainEndX = clickPlayer.getX();
        final float mainEndY = clickPlayer.getY();

        if (XHCustomConfig.getInstance(this).getOpenGLESEnable()) {
            clickPlayer.setX(clickEndX);
            clickPlayer.setY(clickEndY);
            clickPlayer.getLayoutParams().width = (int) clickEndW;
            clickPlayer.getLayoutParams().height = (int) clickEndH;
            clickPlayer.requestLayout();

            mainPlayer.setX(mainEndX);
            mainPlayer.setY(mainEndY);
            mainPlayer.getLayoutParams().width = (int) mainEndW;
            mainPlayer.getLayoutParams().height = (int) mainEndH;
            mainPlayer.requestLayout();
        } else {

            final ValueAnimator valTotal = ValueAnimator.ofFloat(0f, 1f);
            valTotal.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    clickPlayer.setX(clickStartX + (Float) animation.getAnimatedValue() * (clickEndX - clickStartX));
                    clickPlayer.setY(clickStartY + (Float) animation.getAnimatedValue() * (clickEndY - clickStartY));
                    clickPlayer.getLayoutParams().width = (int) (clickStartW + (Float) animation.getAnimatedValue() * (clickEndW - clickStartW));
                    clickPlayer.getLayoutParams().height = (int) (clickStartH + (Float) animation.getAnimatedValue() * (clickEndH - clickStartH));
                    clickPlayer.requestLayout();

                    mainPlayer.setX(mainStartX + (Float) animation.getAnimatedValue() * (mainEndX - mainStartX));
                    mainPlayer.setY(mainStartY + (Float) animation.getAnimatedValue() * (mainEndY - mainStartY));
                    mainPlayer.getLayoutParams().width = (int) (mainStartW + (Float) animation.getAnimatedValue() * (mainEndW - mainStartW));
                    mainPlayer.getLayoutParams().height = (int) (mainStartH + (Float) animation.getAnimatedValue() * (mainEndH - mainStartH));
                    mainPlayer.requestLayout();
                }
            });

            valTotal.setDuration(300);
            valTotal.setInterpolator(new LinearInterpolator());
            valTotal.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    isRuning = true;
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    isRuning = false;
                    clickPlayer.setScalType(StarPlayerScaleType.DRAW_TYPE_CENTER);
                    mainPlayer.setScalType(StarPlayerScaleType.DRAW_TYPE_CENTER);
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    isRuning = false;
                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            valTotal.start();
        }
    }

    private void deleteAllPlayer() {
        if (mPlayerList != null) {
            mPlayerList.clear();
            rl_videoContainer.removeAllViews();
            resetLayout();
        }
    }

    private void deletePlayer(String removeUserId) {
        if (mPlayerList != null && mPlayerList.size() > 0) {
            for (int i = 0; i < mPlayerList.size(); i++) {
                ViewPosition temp = mPlayerList.get(i);
                if (temp.getUserId().equals(removeUserId)) {
                    ViewPosition remove = mPlayerList.remove(i);
                    rl_videoContainer.removeView(remove.getVideoPlayer());
                    resetLayout();
                    if (mPlayerList.size() != 0) {
                        liveManager.changeToBig(mPlayerList.get(0).getUserId());
                    }
                    break;
                }
            }
        }
    }


    private void checkPermission() {//Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
        String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
        PermissionsUtils.getInstance().checkPermissions(ChatRoomActivity.this, permissions, ChatRoomActivity.this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onGranted() {
        String liveId = liveRoom.getLiveId();
        //如果liveId 是空的，则需要新建
        if (TextUtils.isEmpty(liveId)) {

            XHLiveItem liveItem = new XHLiveItem();
            liveItem.setLiveID(IDUtils.genUUID());
            liveItem.setLiveName("");
            liveItem.setLiveType(XHConstants.XHLiveType.XHLiveTypeGlobalPublic);
            try {
                liveManager.createLive(liveItem, new IXHResultCallback() {
                    @Override
                    public void success(Object o) {
                        String liveId = o.toString();
                        Log.i(TAG, "success: 创建直播间成功" + liveId);
                        liveRoom.setLiveId(liveId);
                        prepareLive(liveId);
                    }

                    @Override
                    public void failed(String s) {
                        Log.e(TAG, "failed: 创建直播间失败" + s);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            prepareLive(null);
        }
    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        StringBuilder tips = new StringBuilder();
        for (String permission : deniedPermissionList) {
            if (Manifest.permission.ACCESS_FINE_LOCATION.equals(permission)) {
                tips.append("[位置] ");
            } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permission) || Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)) {
                tips.append("[储存空间] ");
            } else if (Manifest.permission.RECORD_AUDIO.equals(permission)) {
                tips.append("[麦克风] ");
            } else if (Manifest.permission.CAMERA.equals(permission)) {
                tips.append("[相机] ");
            }
        }
        ConfirmDialog dialog = new ConfirmDialog(ChatRoomActivity.this, "提醒", "使用 " + tips + "的权限被禁止，去设置？", "去设置", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });

        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void managerMenu() {
        View popView = getLayoutInflater().inflate(R.layout.live_room_manager_menu_layout, null);
        final PopupWindow popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //计算popupWindow的宽度
//        popupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED);
//        int width= popupWindow.getContentView().getMeasuredWidth();

        popupWindow.showAsDropDown(avatarListView, 0, Utils.dpToPx(3, ChatRoomActivity.this), Gravity.RIGHT);
        popView.findViewById(R.id.rl_manage_live_room).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                showMangerBottomDialog();
            }
        });
        popView.findViewById(R.id.rl_to_topic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                if (TextUtils.equals(myUserInfo.getuId(), liveRoom.getManagerId())) {
                    TopicDetailsActivity.startActivity(ChatRoomActivity.this, liveRoom.getId(), REQUEST_CODE_EDIT_TOPIC);
                } else {
                    TopicDetailsActivity.startActivity(ChatRoomActivity.this, liveRoom.getId());
                }
            }
        });

    }

    private void showMangerBottomDialog() {
        List<String> dialogItems = new ArrayList<>();
        dialogItems.add(CLOSE_CURRENT_LIVE);
        dialogItems.add(FORBID_CHAT);
        dialogItems.add(REMOVE_OUT_LIVE_ROOM);
        if (liveRoom.getStatus() == Constant.LIVE_ROOM_STATUS_FORBID) {
            dialogItems.add(OPEN_LIVE);
        } else {
            dialogItems.add(FORBID_LIVE);
        }

        BottomDialog dialog = new BottomDialog(ChatRoomActivity.this, dialogItems, new BottomDialog.InteractionListener() {
            @Override
            public void onDialogItemViewClick(int position, String itemName) {
                switch (itemName) {
                    case CLOSE_CURRENT_LIVE:
                        if (isLiveStarted) {
                            // TODO: 2019/7/6 应该让管理员 输入关闭的原因
                            if (anchor != null && TextUtils.equals(liveRoom.getManagerId(), anchor.getUId())) {
                                stopLiveToService();
                            } else {
                                managerStopLive();
                            }
                        } else {
                            ConfirmDialog confirmDialog = new ConfirmDialog(ChatRoomActivity.this, "提示", "当前并非直播状态");
                            confirmDialog.show();
                        }
                        break;

                    case FORBID_LIVE:
                        forbidLive();
                        break;

                    case OPEN_LIVE:
                        openLive();

                        break;

                    case FORBID_CHAT:
                    case REMOVE_OUT_LIVE_ROOM:
                        // TODO: 2019/7/6 等待开发
                        ConfirmDialog confirmDialog = new ConfirmDialog(ChatRoomActivity.this, "提示", "开发中...");
                        confirmDialog.show();
                }
            }
        });
        dialog.show();
    }

    /**
     * 开放直播
     */
    private void openLive() {

        RetrofitManager.getInstance().createRequest(LiveService.class)
                .openLive(liveRoom.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult body = response.body();

                        if (!response.isSuccessful() || body == null) {

                            Log.e(TAG, "onResponse: 返回数据为空");

                            return;
                        }
                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            return;
                        }

                        showToast_v1("开放直播操作完成");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    /**
     * 禁止直播
     */
    private void forbidLive() {

        RetrofitManager.getInstance().createRequest(LiveService.class)
                .forbidLive(liveRoom.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult body = response.body();

                        if (!response.isSuccessful() || body == null) {

                            Log.e(TAG, "onResponse: 返回数据为空");

                            return;
                        }
                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            return;
                        }

                        showToast_v1("禁止直播操作完成");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();
                    }
                });

    }

    private void showPopupWindow(final Context context, @NonNull View anchorView) {
        String ACCUSATION = "内容举报";
        String ERROR_REPORT = "故障申报";
        String MANAGER = "管理焦点";
        String TO_TOPIC_DETAIL = "进入详情";
        List<String> popWindowItems = new ArrayList<>();
        if (TextUtils.equals(myUserInfo.getuId(), liveRoom.getManagerId()) || myUserInfo.getLiveRoomSupperManager()) {
            popWindowItems.add(MANAGER);
        } else {
            popWindowItems.add(ACCUSATION);
            popWindowItems.add(ERROR_REPORT);
        }
        popWindowItems.add(TO_TOPIC_DETAIL);
        final ListPopupWindow popupWindow = new ListPopupWindow(context);
        popupWindow.setAdapter(new MenuArrayAdapter(context, R.layout.right_menu_item, R.id.tv_dialog_item, popWindowItems));
        popupWindow.setWidth(Utils.dpToPx(120, context));//也可以设置具体的值。容易出错的地方
        popupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
        popupWindow.setHorizontalOffset(Utils.dpToPx(-5, context));
        popupWindow.setAnchorView(anchorView);//设置参照控件
        popupWindow.setDropDownGravity(Gravity.END);//设置对齐方式。
        // popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.tx_pop_bg_1));
        popupWindow.setModal(true);//模态框，设置为true响应物理键
        popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                String s = popWindowItems.get(position);
                if (TextUtils.equals(s, TO_TOPIC_DETAIL)) {
                    if (TextUtils.equals(myUserInfo.getuId(), liveRoom.getManagerId())) {
                        TopicDetailsActivity.startActivity(ChatRoomActivity.this, liveRoom.getId(), REQUEST_CODE_EDIT_TOPIC);
                    } else {
                        TopicDetailsActivity.startActivity(ChatRoomActivity.this, liveRoom.getId());
                    }
                } else if (TextUtils.equals(s, MANAGER)) {
                    showMangerBottomDialog();
                } else if (TextUtils.equals(s, ERROR_REPORT)) {

                    ConfirmDialog dialog = new ConfirmDialog(ChatRoomActivity.this, "提示", "确定提交错误报告吗", true);
                    dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                        @Override
                        public void confirm() {
                            liveErrorReport();
                        }
                    });
                    dialog.show();
                } else if (TextUtils.equals(s, ACCUSATION)) {

                    ConfirmDialog dialog = new ConfirmDialog(ChatRoomActivity.this, "提示", "确定举报视频内容吗", true);
                    dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                        @Override
                        public void confirm() {
                            liveAccusation();
                        }
                    });
                    dialog.show();
                }
            }
        });
        popupWindow.show();
    }

    /**
     * 直播内容举报
     */
    private void liveAccusation() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance()
                .createRequest(LiveService.class)
                .liveAccusation(liveRoom.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "举报直播出错:" + response.code());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "举报直播出错:" + result.getMsg());
                            showToast(iv_liveRoomIdle, getString(R.string.system_busy));
                            return;
                        }

                        showToast_v1("举报完成");

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: 举报直播出错");
                    }
                });
    }

    /**
     * 直播故障报告，
     * 避免主播掉线后，关注却没收到错误回调，导致直播一直被占用
     */
    private void liveErrorReport() {
        RetrofitManager.getInstance()
                .createRequest(LiveService.class)
                .liveErrorReport(liveRoom.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "提交直播错误报告失败:" + response.code());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "提交直播错误报告失败:" + result.getMsg());
                            showToast(iv_liveRoomIdle, getString(R.string.system_busy));
                            return;
                        }
                        showToast_v1("提交错误报告完成");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: 提交直播错误报告失败");
                    }
                });
    }


    @Override
    public void onReConnectSuccess() {

    }

    @Override
    public void onConnectInterruption() {

    }

    @Override
    public void onImLoginSuccess() {
        //游客 在直播间去到登录页面登录或者注册后，因账户变动，需要重新进入直播间
        Log.d(TAG, "onImLoginSuccess: 聊天服务器登陆成功");
        myUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        messageView.setLoinUserInfo();
        liveRoomService.quitLiveRoom();//需要先调用一次登出，让前面一个登录在本直播间的用户退出房间，否则他的id ,将会一直在 直播间中，
        initLiveRoom();
        //liveRoomService = IMSClientBootstrap.getInstance().getLiveRoomService();
        //liveRoomService.setMessageListener(getMessageListener());
        liveRoomService.changeAccountJoinLiveRoom(liveRoom);
//        //切换账户重新登录后，把用户添加进头像列表
        avatarListView.loginUserJoin(myUserInfo);
    }
}
